﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Diagnostics;

namespace Business.Entities
{
    /// <summary>
    /// Locally stored data to keep track of sync history
    /// </summary>
    public class SyncHistory
    {
        private static SyncHistory _instance;

        /// <summary>
        /// Filename of the synchistory file
        /// </summary>
        public static string Filename = "synchistory.json";
        /// <summary>
        /// List of existing outlook ids by last sync
        /// </summary>
        public List<string> OutlookIds { get; set; }
        /// <summary>
        /// List of existing outlook ids by last sync
        /// </summary>
        public List<string> GoogleIds { get; set; }

        /// <summary>
        /// Timestamp of last synchornization
        /// </summary>
        public DateTime LastSyncTime { get; set; }
        /// <summary>
        /// Timestamp of last modification of any sort in the outlook task list
        /// </summary>
        public DateTime OutlookLastModified { get; set; }


        public SyncHistory()
        {
            OutlookIds = new List<string>();
            GoogleIds = new List<string>();
        }

        public static string GetSyncHistoryFullFileName()
        {
            return  Context.ConfigPath + Path.DirectorySeparatorChar + Filename;
        }

        private static SyncHistory Load()
        {
            try
            {
                //string text = File.ReadAllText(Context.ConfigPath + "/" + Filename); 
                string filename = GetSyncHistoryFullFileName();
                string text = LoadFile(filename);
                return Context.JsonApi.Deserialize<SyncHistory>(text);
            }
            catch (IOException)
            {
                Trace.WriteLine("No synch history found - using default constructor");
                return new SyncHistory();
            }

        }

        public static SyncHistory GetInstance()
        {
            if (_instance == null)_instance = Load();
            return _instance;
        }

        /// <summary>
        /// Delets all synchronization history
        /// </summary>
        public static void Wipe()
        {
            string file = GetSyncHistoryFullFileName();
            if (File.Exists(file)) File.Delete(file);
            _instance = null;
        }


        public void Save()
        {
            string text = Context.JsonApi.Serialize(this);
            //File.WriteAllText(Context.ConfigPath + "/" + Filename, text);
            string filename = GetSyncHistoryFullFileName();
            SaveFile(filename, text);
        }

        private static void SaveFile(string filename, string text)
        {
            FileStream fs = File.Create(filename);
            TextWriter tw = new StreamWriter(fs);
            tw.Write(text);
            tw.Close();
            fs.Close();
        }

        private static string LoadFile(string filename)
        {
            FileStream fs = File.OpenRead(filename);
            StreamReader sr = new StreamReader(fs);
            string text = sr.ReadToEnd();
            fs.Close();
            return text;
        }

        internal void SetData(TasksRoot tasksRoot)
        {
            OutlookIds.Clear();
            GoogleIds.Clear();
            foreach (TaskList list in tasksRoot.lists)
            {
                foreach (Task task in list.child_entity)
                {
                    if (!String.IsNullOrEmpty(task.OutlookId)
                        && !OutlookIds.Contains(task.OutlookId))
                    {
                        OutlookIds.Add(task.OutlookId);
                    }
                    if (!String.IsNullOrEmpty(task.id)
                        && !GoogleIds.Contains(task.id))
                    {
                        GoogleIds.Add(task.id);
                    }
                }
            }
        }
    }
}
